package com.buddy.rpc.sdk.framework;

import com.buddy.rpc.sdk.http.HttpClient;
import com.buddy.rpc.sdk.register.RemoteRegister;

import java.lang.reflect.Proxy;

/**
 * @author buddy
 * @date 2021/12/21
 */
public class ProxyFactory {
    public static <T> T getProxy(Class<T> interfaceClass) {
        Object o = Proxy.newProxyInstance(interfaceClass.getClassLoader(),
                new Class[]{interfaceClass},
                (proxy, method, args) -> {
                    Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                    // 从注册中心获取url
                   Url url =  RemoteRegister.getRandom(interfaceClass.getName());
                    HttpClient httpClient = new HttpClient();
                    String result = httpClient.send(url.getHostname(),url.getPort(),invocation);
                    return result;
                }
        );
        return (T) o;
    }
}
